/**
 * 为指定对象添加指定的属性
 * @param {Object} C 待添加的对象
 * @param {Object} D 要添加的属性
 * @param {Object} B 默认属性
 * @return {Object}
 */
function apply(C, D, B) {
	if (B) {
		apply(C, B);
	}
	if (C && D && typeof D == "object") {
		for (var A in D) {
			C[A] = D[A];
		}
	}
	return C;
};
apply(Function.prototype, {
	/**
	 * 为一个方法创建一个代理
	 * @param {} obj
	 * @param {} args
	 * @param {} appendArgs
	 * @return {}
	 */
	createDelegate : function(obj, args, appendArgs){
        var method = this;
        return function() {
            var callArgs = args || arguments;
            if(appendArgs === true){
                callArgs = Array.prototype.slice.call(arguments, 0);
                callArgs = callArgs.concat(args);
            }else if(typeof appendArgs == "number"){
                callArgs = Array.prototype.slice.call(arguments, 0);
                var applyArgs = [appendArgs, 0].concat(args);
                Array.prototype.splice.apply(callArgs, applyArgs);
            }
            return method.apply(obj || window, callArgs);
        };
    },
    /**
     * 使方法延迟执行
     * @param {} millis
     * @param {} obj
     * @param {} args
     * @param {} appendArgs
     * @return {Number}
     */
    defer : function(millis, obj, args, appendArgs){
        var fn = this.createDelegate(obj, args, appendArgs);
        if(millis){
            return setTimeout(fn, millis);
        }
        fn();
        return 0;
    }
});
function getSelectedBy(selected, field) {
	var arr = [];
	for (var i = 0; i < selected.length; i++) {
		var v = selected[i][field];
		if (v)
			arr.push(v);
	}
	return arr.join(",");
}
apply(Array.prototype, {
	contains : function(obj) {
		return this.indexOf(obj) != -1;
	},
	indexOf : function(obj) {
		for(var i = 0; i < this.length; i++) {
			if (this[i] == obj) return i;
		}
		return -1;
	},
	remove : function(obj) {
		var index = this.indexOf(obj);
		if (index != -1) this.splice(index, 1);
	}
});
apply(String.prototype, {
	trim : function(){
        return String(this).replace(/^\s+|\s+$/g, "");
    }
});
$(function() {
/**
 * 将form的各个参数以对象的形式返回
 * 
 * @param {Boolean}
 *            toString 是否以String形式返回
 * @author xjf@2011-09-26
 */
$.fn.extend({
	getFormParams : function(toString) {
		if (toString === true) {
			var param = [];
			return this.each(function() {
						var param = this.serialize();
						param.push(isNull(param) ? "" : "&" + param);
					});
			return param.join("");
		} else {
			var obj = {};
			this.each(function() {
						var param = $(this).serialize();
						var strs = param.split("&");
						$(strs).each(function(i, n) {
							if (!n)
								return true;
							var kv = n.split("=");
							if (kv[1]) {
								var val = decodeURIComponent(kv[1]);
								if (obj[kv[0]] && isArray(obj[kv[0]])) {
									obj[kv[0]].push(val);
								} else if (obj[kv[0]]
										&& !isArray(obj[kv[0]])) {
									obj[kv[0]] = [obj[kv[0]]];
									obj[kv[0]].push(val);
								} else {
									obj[kv[0]] = val;
								}
							}
						});
					});
			return obj;
		}
	},
	
	/**
	 * 将一个FORM中的字段以HTML的形式转换隐藏域,用于获取FORM中的参数
	 */
	getParamsHtml : function() {
		var html = [];
		this.each(function(i, form) {
					var f = $(form);
					f.find("input,select,textarea").each(function(j, n) {
						if (n.name && n.value
								&& f.children(n.name).length == 0) {
							html.push("<input type='hidden' name='"
									+ n.name + "' value='" + n.value
									+ "'/>");
						}
					});
				});
		return html.join("");
	},
	appendParamsForm : function(formName) {
		this.each(function(i, form) {
					formName = $(formName);
					$(form).append(formName.getParamsHtml());
				});
	},
	formLoadData : function(url, param) {
		var _this = this;
		if (this.tagName == "FORM" || this.tagName == "form")
			this.reset();
		$.getJSON(url, param, function(data) {
					if (!data)
						return;
					_this.each(function(i, form) {
								$(form).find("input,select,textarea").each(
										function(i, field) {
											var val = data[field.name
													|| field.id];
											if (val)
												$(field).val(val);
										});
							});
				});
	},
	sizeAndPos : function() {
		var th = $(this);
		var offset = th.offset();
		offset.height = th.height();
		offset.width = th.width();
		return offset;
	},
	setSize : function(sizeObj) {
		return this.each(function(i, el) {
					var e = $(el);
					e.height(sizeObj.height || e.height());
					e.width(sizeObj.width || e.width());
					e.offset(sizeObj || e.offset());
				});
	},
	mask : function(html, noText) {
		return this.each(function(i, el) {
			var exists = $.data(el, "masker");
			if (exists) return true;
			var e = $(el);
			var top = e.height() / 2 - 8;
			var msg = null;
			if (typeof html === 'boolean') noText = html;
			if (noText !== false) {
				msg = $("<span></span>").css({
					"margin-left" : "auto",
					"margin-right" : "auto",
					"margin-top" : top,
					"width" : "auto",
					"height" : "16px",
					"padding" : "12px 5px 10px 30px",
					"color" : "#222",
					"z-index" : "99999",
					"border" : "3px solid #447799",
					"background" : "#fff url('/lbm/js/jquery/js/themes/default/images/pagination_loading.gif') no-repeat scroll 5px 10px",
					"display" : "inline-block"
				}).html(html || "加载中，请稍候...");
			}
			var div = $("<div></div>").css({
						"position" : "absolute",
						"background-color" : "#FDFCFE",
						"z-index" : "99998",
						"text-align" : "center"
					}).setSize(e.sizeAndPos())
					.appendTo(document.body);
			if (noText !== false) {
				div.append(msg);
			} else {
				div.css({"opacity": 0.7, "background" : "#fff url('/lbm/themes/shareResources/images/loading.gif') no-repeat center center"});
			}
			$.data(el, "masker", div);
		});
	},
	unmask : function() {
		return this.each(function(i, el) {
					var div = $.data(el, "masker");
					$(div).remove();
					$.removeData(el, "masker");
				});
	}
});
	/**
	 * 设置默认的ajax选项，用以全局监控
	 */
	$.ajaxSetup({
				beforeSend : function(xhr) {
					if (this.dataType == "html" || this.dataType == "script")
						return;
					$('body').mask(false);
				},
				complete : function() {
					if (this.dataType == "html" || this.dataType == "script")
						return;
					$('body').unmask();
				}
			});
	/**
	 * 表单提交时显示进度条，防止重复提交
	 */
	$("form").live('submit', function() {
				$('body').mask(false);
			});
});
/**
 * 是否非空
 * @param {} v
 * @return {}
 */
function notNull(v) {
	return v != null && v != "" && typeof v != "undefined";
}
/**
 * 是否为空
 * @param {} v
 * @return {}
 */
function isNull(v) {
	return v == null || v == "" || typeof v == "undefined";
}

/**
 * 判断某个对象是否为数组
 * 
 * @param {Array}
 *            arr
 * @return {}
 */
function isArray(arr) {
	return (typeof arr == "object") && (typeof arr.length == "number")
			&& (typeof arr.slice == "function");
}
function dump(obj) {
	if (!obj) return;
	var s = "";
	if (isArray(obj)) {
		for (var i = 0; i < obj.length; i++) {
			s += "[" + i + ":" + obj[i] + "]\n";
		}
		return s;
	}
	for (var p in obj) {
		s += "[" + p + "=" + obj[p] + "]\n";
	}
	return s;
}
/**
 * 将JSON字符串转换成JS对象
 * @param json
 */
function decode(json) {
	if (typeof json != "string") return json;
	if (isNull(json)) return null;
	return eval("(" + json + ")");
}
/**
 * 无跳转提交FORM。（注意： form的action必须设置正确）
 * @param {HTMLElement} form 要提交的FORM
 * @param {Function} success 提交成功以后要执行的代码,有两个参数req,status
 * @param {Function} failure 提交失败要执行的代码,有两个参数req,status
 */
function submit(form, success, failure) {
	form = $(form);
	if (!form || form.size() == 0)
		return;
	var param = form.serialize();
	$.ajax({
				url : form.attr("action") || "",
				data : param,
				success : function(data, status) {
					if ($.isFunction(success))
						success.call(this, data, status);
				},
				error : function(data, status) {
					if ($.isFunction(failure))
						failure.call(this, data, status);
				},
				cache : false,
				dataType : "json",
				type : "POST",
				contentType : "application/x-www-form-urlencoded;charset=utf-8"
			});
}
function isSuccess(res, status) {
	var txt = res.responseText || res;
	if (txt) {
		var obj = decode(txt);
		return obj.success && status == "success";
	}
	return false;
}
function inputClean(e) {
	var p = $(e).parent();
	p.find('input[type=text]').each(function() {
				$(this).val('');
			});
}

/**
 * 在右下角显示一个提示框
 * @param {} txt
 */
function showTip(txt) {
	$.messager.show({
		title : "提示",
		msg : txt,
		timeout : 2200
	});
}
/**
 * 将页面高度宽度自适应
 * @param {} container
 */
function fit(container) {
	container = container || "#container";
	container = $(container);
	if (!container || !container.length)
		return;
	var p = $(container.parent() || 'body');
	var cfg = {
		width : "100%",
		height : "100%"
	};
	p.css(cfg);
	container.css({
				width : "100%",
				height : "auto",
				position : "relative"
			}).attr("fit", "true");
	container.layout();
	$(window).resize(function() {
				container.layout();
			});
}

/**
 * url还是jsondata，是否单选复选，是否要选择才能输入，是否填充第三方元素，填充完毕后动作
 */
function jqueryAutocomplete(ele, urlorData, config, resultFn) {
	var options = {
		dircolumns : ['name'],
		resultcolumn : 'username',
		scroll : true,
		scrollHeight : 180,
		minChars : 1,
		matchCase : false,// 不区分大小写
		mustMatch : false,// 必须是匹配的
		matchContains : true,
		minchar : 1,// 最小响应字符数量
		selectFirst : false
		// 默认不选中第1条
	};

	$(ele).autocomplete(urlorData, apply(options, config, {
				// 格式化选项,由于返回的数据是JSON格式,现在要转成HTML以TABLE形式显示
				// 考虑的长度，暂时只支持3列
				formatItem : function(row, i, max) {
					var dc = this.dircolumns;
					var dclen = dc.length;
					var item = "<table id='auto" + i
							+ "' style='width:100%;'><tr>";
					item += "<td align='left'>" + row[dc[0]];
					item += "</td> ";
					item += dclen > 1
							? "<td align='right' style='color:green;'>"
									+ row[dc[1]] + "</td>"
							: "";
					item += dclen > 2 ? "<td align='right'>" + row[dc[2]]
							+ "</td>" : "";
					item += "</tr></table>";
					return item;
				},
				formatMatch : function(row, i, max) {
					var dc = this.dircolumns;
					var dclen = dc.length;
					return row[dc[0]] + (dclen > 1 ? " " + row[dc[1]] : "")
							+ (dclen > 2 ? " " + row[dc[2]] : ""); // 用户输入的内容在哪些数据项里面搜索
				},

				// 格式化结果,当选中时返回具体的值
				formatResult : function(row, i, max) {
					return row[this.resultcolumn];
				}
			}));
	$(ele).result(function(event, item) {
				if (resultFn) {
					resultFn(event, item);
				}
			});

}
/**
 * 用户信息自动填充
 * 
 * @param {}
 *            ele
 */
function userNoteAutocomplete(username_input, userid_hidden) {
	$.getJSON("/lbm/loginingController.do?method=getUserToJson", {},
			function(data) {
				jqueryAutocomplete($('#' + username_input), data.rows, {
							dircolumns : ['userNote'],
							resultcolumn : 'userNote'
						}, function(event, item) {
							if (userid_hidden)
								$('#' + userid_hidden).val(item['userid']);
						});
			});

}
/**
 * 用户信息自动填充
 * 
 * @param {}
 *            ele
 */
function userNameAutocomplete(username_input, userid_hidden) {
	$.getJSON("/lbm/loginingController.do?method=getUserToJson", {},
			function(data) {
				jqueryAutocomplete($('#' + username_input), data.rows, {
							dircolumns : ['userName'],
							resultcolumn : 'userName'
						}, function(event, item) {
							if (userid_hidden)
								$('#' + userid_hidden).val(item['userid']);
						});
			});

}
function setPageValue(){
	var page=$(".pagination-num[name=page]");
	    if(page.length>0){
	    page.val(1);
	    }
	}
function toObject(str) {
	var obj = {};
	if (!str) return obj;
	var strs = str.split(",");
	for (var i = 0; i < strs.length; i++) {
		var s = strs[i].split(" ");
		if (s.length == 2) {
			obj[s[0]] = s[1];
		}
	}
	return obj;
}
function initGrid(form,events){

	$("#btn_query").bind('click',setPageValue);
var form = form || $("form").get(0);
events = events || {};
//事件
this.events = ["onpagefirst", "onpagelast", "onpageprev", "onpagenext",
		"onjump", "onpagerefresh", "onbeforeselect", "onafterselect", "onsort"];
if (!form) return;
$.each(this.events, function(i, e) {
	form.bind(e, events[e] || events["handler"] || function(){});
	events[e] = events[e] || events["handler"];
});
var page = form.find("input[name='page']");
var pages = form.find("input[name='pages']");
var rows = form.find("select[name='rows']");
if (rows.length == 0) rows = form.find("input[name='rows']");
form.keypress(function(e) {
	if (e.keyCode == 13) {
		return false;
	}
});
var switchButton = function() {
	if (parseInt(page.val()) == 1) {
		first.addClass("l-btn-disabled");
		priv.addClass("l-btn-disabled");
	}
	if (parseInt(page.val()) == parseInt(pages.val()) || parseInt(pages.val()) <= 0) {
		last.addClass("l-btn-disabled");
		next.addClass("l-btn-disabled");
	}
}
var first = form.find("a[icon=pagination-first]").click(function(){
	if (parseInt(page.val()) == 1) return;
	page.val(1);
	form.trigger("onpagefirst", [page.val(), rows.val()]);
	switchButton();
	if (!$.isFunction(events["onpagefirst"])) {
		form.submit();
	}
});
var last = form.find("a[icon=pagination-last]").click(function(){
	if (parseInt(page.val()) >= parseInt(pages.val())) return;
	page.val(pages.val());
	form.trigger("onpagelast", [page.val(), rows.val()]);
	switchButton();
	if (!$.isFunction(events["onpagelast"])) {
		form.submit();
	}
});
var priv = form.find("a[icon=pagination-prev],a[name=page-priv]").click(function(){
	if (parseInt(page.val()) <= 1) return;
	page.val(parseInt(page.val()) - 1);
	form.trigger("onpageprev", [page.val(), rows.val()]);
	switchButton();
	if (!$.isFunction(events["onpageprev"])) {
		form.submit();
	}
});
var next = form.find("a[icon=pagination-next],a[name=page-next]").click(function(){
	if (parseInt(page.val()) >= parseInt(pages.val())) return;
	page.val(parseInt(page.val()) + 1);
	form.trigger("onpagenext", [page.val(), rows.val()]);
	switchButton();
	if (!$.isFunction(events["onpagenext"])) {
		form.submit();
	}
});
switchButton();
page.change(function() {
	var val = $(this).val();
	if (isNaN(val)) {
		alert("请输入数字!");
		return;
	} else if (parseInt(val) > parseInt(pages.val())) {
		alert("不能超过最大页数！");
		return;
	} else if (parseInt(val) <= 0) {
		alert("请输入大于0的值！");
		return;
	}
	form.trigger("onjump", [page.val(), rows.val()]);
	if (!$.isFunction(events["onjump"])) {
		form.submit();
	}
});
var freshMethod = function(){
	var row = rows.val();
	if (isNaN(row)) {
		alert("请输入数字!");
		return;
	} else if (parseInt(row) > 300) {
		alert("每页最多显示300条，请重新输入！");
		return;
	} else if (parseInt(row) <= 0) {
		alert("请输入大于0的值！");
		return;
	}
	rows.val(parseInt(row));
	form.trigger("onpagerefresh", [page.val(), rows.val()]);
	if (!$.isFunction(events["onpagerefresh"])) {
		form.submit();
	}
};
form.find("a[icon=pagination-load]").click(freshMethod);
rows.change(function(){
	page.val("1");
	freshMethod();
});
form.find("#selectAll").click(function() {
	var checked = this.checked;
	form.find(".checkbox").each(function(i) {
		$(this).children(":checkbox").attr("checked",checked);
		if (checked) {
			$(this).parent().addClass("data-grid-row-selected");
		} else {
			$(this).parent().removeClass("data-grid-row-selected");
		}
	});
});
var click = function(event){
	var chk = $(this).find(":checkbox");
	if (chk.size() > 0 && event.target.tagName != "INPUT") {
		chk.attr("checked", !chk.attr("checked"));
	}
	$(this).toggleClass("data-grid-row-selected");
	form.trigger("onrowselect", [form, $(this)]);
};
form.find(".data-grid TBODY").find("tr").each(function(i, tr) {
	var cur = $(tr);
	if (i%2 != 0) cur.attr("class","row-color");
	//$(this).find("td").contents().wrap("<div class='ellipsis'></div>");
	cur.click(click);//行单击事件
});
var sortObj = toObject(form.find("input[name=orders]").val());
var sortHandler = function(field) {
	var old = sortObj[field];
	sortObj = {};//这句代码可以控制只有一个排序条件有效
	if (!old) {
		sortObj[field] = "ASC";
	} else if (old == "ASC") {
		sortObj[field] = "DESC";
	}
	var sort = form.find("input[name='orders']");
	sort.val(serialize(sortObj));
	if (typeof events["onsort"] == "function") {
		form.trigger("onsort", sortObj);
	} else {
		form.submit();
	}
};
form.find(".data-grid-header").children().each(function(i) {
	var th = $(this);
	th.resizable({
		handles : "e,w",
		minWidth : 10
	});
	var field = th.attr("sortname");
	if (!field) return true;
	var span = $(this).children("span");
	if (span.length == 0) span = $("<span class='datagrid-sort-icon'>&nbsp;</span>").appendTo(this);
	var old = (sortObj[field] || "").toUpperCase();
	if (!old) {
		th.removeClass("datagrid-sort-asc datagrid-sort-desc").remove("span");
	} else if (old == "ASC") {
		th.addClass("datagrid-sort-asc").removeClass("datagrid-sort-desc");
	} else if (old == "DESC"){
		th.addClass("datagrid-sort-desc").removeClass("datagrid-sort-asc");
	}
	
	th.click(sortHandler.createDelegate(sortHandler, [field]));
});
form.getSelections = function() {
	var selected = [];
	form.find("tbody").children("tr").each(function (i, tr) {
		var obj = {"length" : 0};
		$(tr).find(":checked").each(function(j, chk) {
			var td = $(chk).parent();
			var field = td.attr("field") || j;
			obj[field] = td.children("input").val() || td.text();
			obj.length++;
		});
		if (obj.length > 0) {
			delete obj.length;
			selected.push(obj);
		}
	});
	return selected;
}
form.getRow = function(index) {
	return form.find("tbody").find("tr:eq(" + index + ")");
}
form.removeRow = function(index) {
	return form.getRow(index).remove();
}
if (typeof window.getSelected != "function") {
	window.getSelected = function(single,scope) {
		var f = scope || form;
		var chks = f.find(".checkbox").find(":checked");
		if (chks.size() == 0) {
			alert("请选择记录！");
			return;
		}
		if (single && chks.size() > 1) {
			alert("只能选择1条记录！");
			return;
		}
		var ids = new Array();
		chks.each(function(i) {
			var val = $(this).val();
			if (val && val != "on") {
				ids.push(val);
			}
		});
		return ids.join(",");
	};
}
}
